import pickle, base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, response):

    # 先尝试获取cookie中购物车的数据
    cart_str = request.COOKIES.get('carts')
    if cart_str is None:
        return

    # 将cookie字符串转换成字典
    cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()
    user = request.user
    # 遍历cookie大字典
    for sku_id, cart_dict in cart_dict.items():
        # 将sku_id和count和redis的hash中添加,存在就覆盖,不存在就是新建
        pl.hset('carts_%s' % user.id, sku_id, cart_dict['count'])
        # 判断selected 动态把sku_id添加和删除set
        if cart_dict['selected']:
            pl.sadd('selected_%s' % user.id, sku_id)
        else:
            pl.srem('selected_%s' % user.id, sku_id)

    pl.execute()
    # # 将cookie购物车数据清楚
    response.delete_cookie('carts')
